package com.wx.house.manager.api.fileupload.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wx.house.common.base.ProjectConfiguration;
import com.wx.house.core.pojo.dto.fileload.AttaUploadDto;
import com.wx.house.manager.api.fileupload.config.IpConfiguration;
import com.wx.house.manager.api.fileupload.service.FileUploadService;
import com.wx.house.manager.api.fileupload.util.ZimgClient;
import com.wx.house.common.util.IDUtils;
import com.wx.house.core.mapper.fileupload.AttaUploadMapper;
import com.wx.house.core.pojo.po.fileupload.AttaUpload;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

/**
 * @Title:
 * @BelongProjecet com-wx-house
 * @BelongPackage com.wx.house.api.fileupload.service.impl
 * @Description:
 * @Author: yxc
 * @Date: 2019/11/11 9:26
 * @Version V1.0
 */
@Slf4j
@Service
public class FileUploadServiceImpl extends ServiceImpl<AttaUploadMapper, AttaUpload> implements FileUploadService {
@Resource
private AttaUploadMapper attaUploadMapper;
@Resource
private ProjectConfiguration projectConfiguration;

@Override
public AttaUpload multiUploads(MultipartFile file, String type, String id) {
	String fileName = null;
	AttaUpload upload = new AttaUpload();
	try {
		if (file.isEmpty()) {
			log.error("上传失败，上传文件为空");
		} else {
			Path path = Paths.get(projectConfiguration.getStaticResource().getStaticResourcePath());
			if (!Files.exists(path)) {
				Files.createDirectories(path);
			}
			//存入数据库
			upload.setId(id);
			upload.setType(type);
			//获取上传文件名，受浏览器影响
			String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			upload.setAttaName(file.getOriginalFilename());
			upload.setFileSuffix(fileSuffix);
			//生成文件名称
			fileName = IDUtils.genImageName();
			String pathName = projectConfiguration.getStaticResource().getStaticResourcePath() + fileName + fileSuffix;
			File dest = new File(pathName);
			file.transferTo(dest);
			dest.setWritable(true);
			upload.setPath(pathName);
			//设置文件预览路径
			upload.setUrl(fileName + fileSuffix);
			upload.setCreatTime(new Date());
			//存入数据库
			this.attaUploadMapper.insert(upload);
			System.gc();
		}
	} catch (IOException e) {
		log.error("上传失败，原因： " + e);
	}
	return upload;
}

@Override
public void getImg(String name, HttpServletResponse response) {
	response.setContentType("image/jpeg;charset=utf-8");
	response.setHeader("Content-Disposition", "inline; filename=girls.png");
	ServletOutputStream outputStream = null;
	try {
		outputStream = response.getOutputStream();
		outputStream.write(Files.readAllBytes(Paths.get(ZimgClient.imgLocalpath).resolve(name)));
		outputStream.flush();
		outputStream.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
	@Override
	public AttaUpload upload(AttaUploadDto attaUploadDto) {
        //对字节数组字符串进行Base64解码并生成图片
		//从字符串中获取图片后缀
		AttaUpload upload = new AttaUpload();
		String fileName = null;
		String fileNameSuffix="."+attaUploadDto.getEncodedImageStr().split(";base64,")[0].split("/")[1];
		String imgStr=attaUploadDto.getEncodedImageStr().split(";base64,")[1];
		BASE64Decoder decoder = new BASE64Decoder();
		try
			{
					Path path = Paths.get(projectConfiguration.getStaticResource().getStaticResourcePath());
					if (!Files.exists(path)) {
						Files.createDirectories(path);
					}
			//Base64解码
			byte[] bytes = decoder.decodeBuffer(imgStr);
			//文件保存路径
			fileName=IDUtils.genImageName();
	        String pathName=projectConfiguration.getStaticResource().getStaticResourcePath() + fileName + fileNameSuffix;
			OutputStream out = new FileOutputStream(pathName);
		    IOUtils.write(bytes,out);
			out.flush();
			out.close();
			//保存数据库
				//存入数据库
				upload.setId(IDUtils.genItemId(13)+"");
				upload.setType(attaUploadDto.getType());
				//获取上传文件名，受浏览器影响
				upload.setAttaName(attaUploadDto.getFileUploadPath());
				upload.setFileSuffix(fileNameSuffix);
				upload.setPath(pathName);
				//设置文件预览路径
				upload.setUrl(fileName + fileNameSuffix);
				upload.setCreatTime(new Date());
				attaUploadMapper.insert(upload);
			}
			catch (Exception e)
			{
              e.printStackTrace();
              log.error("手机文件上传出错"+e);
				System.out.println("文件上传失败");
           }
       return upload;
	}
	public static void main(String[] args) throws IOException {
	//String s=" hLSduSJpA0saxeQ+fwT47FZJpVhxlRZoy0wp5wsiL+qzhIWCxfqlQqaptE0ROt3T15sqJSijuVkhMKMpJXgLj9jwvVDWiaZLGFxTeCuLxJUZO4HLu3WB6pfA33o8j1Dy+L0v1xx8A/uNYYOSiylDOrTvssyzj1eOAwpGAsqtp3WkV46b07xuH4zlsDGyYu1lRSgyRyS9uZRHLGunaYxSpTIwkWRArAlNXXXx85vB4+HBi4EuIrx5S1LJMsgDCTUyYwD7xuHVCVXS1ZdjqN2Mfq59p/znPnZMfQHKxzZUpxmysKeWUdyF0/UeN3llmkaMosojgIEyEHIJcTKFzU1GSspLYbg+/GCyQba7eRUFllnpfVscSyHdBwmCIDebzRiyVBdHXefg+mOL4hpUwcDFxUJUoIoIkUKAVsBAGJ1aiJCx8Ahybb6tMMPZvRgBfkagEUKq1N+R59iSbBYEha1DxvzV0hndXTdJRZMq8hiztiTpkQPjxx5CiNkiRpNFmeQSIojhVtW2Rn3pDuZmDex2ooLDDwxFrsSQCBQJIs+wBJ1JBXGW0qC0XbdrLHsA1fIFBmlerWrqTnbuCKFALFiYW6atMGBVprHS5YY5dS5AoRtL241aoW/gsxJJG48MdQ8mpBql1zzfQfRHPTyJyfEcXlzESId44/7hu5GpbdSSH3jjUUykPCkiMrwyGJtgsFcOFZgCjaEKobyraMVZiFLGrtmC+aDVqfPiX4i+ZZ/m4dTScxm4nD/AOpJlY2Vk5EzwQwqzjsQywTzsI37k0r4jsrF2qMvjtslmOvML7rTMi7o8raZUvGffGFxm3kKPAfe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7R3C0tqAHbUte2o3ck6NZoWd2jDEsVaMFPBWVEcdsKy+yyCNQq/8ATyAUBXcCsk4NjMY4d2pJ8xtzJCqKDLVLxToQhYhuMMljFviVNRjY09rdKhkxaJYf7tUkd1V0hDOLL0e6pcxu43BuNklIjLyKwBYAEnC4BlClTWiyMyKsh3PnYUXLCZe2gBrRmLIFGwdX8VWZWT1SwpZwSZGBD6qgG6kg2t+gFEMd6K2bBwJp5ljjSQRAMQA7kyOxEdqpLH9NY7kchR5DhGB7iHHUmgMpflJXOShRhyU+DKlcNB1ajoQZKxgxJRu4xlJFMRw1ebWrfDZ0Pg4mSVp8ibsuSqwAMT7IqqBEGrV9SjHVk9o2EcaAg7ClzcteOx8PGxmxJBLGzFSWLxsjySFo7Ql2lCIFA3Vi9rSKPorjOHjQI8qB5AVBUgkAp4oLRUKxYUtnwBTMC13p+nEzMcRxBldUBU6o8ocKSU3LEKsspUMLrdxq+ho0PUaGsBKOrNYrbvSosovLKlKxtlnPgOrnptTThMgRhVxjTEpXFNnnmXthq7ujcPmyQyDHZgjL5jFFSsij3UhTaAKVK0oRmDhSTa/WxeOkEkKMVYMGuQsoMblSEUHa9vMYq9tSutp+ko1hl48+BlMJY2jmV2UCRYscNrshepDqyaANHIY2jaSRQS2tT2Hg+T7rJTsHWu7EGUF2RQwMau5tHY6CyGZmYCpCrfWt+ZrQanqzxj65NfSjzS+AMg+/O6jo6U4wl8uAWP0mC4t2YX9PGL62phSsdIu4QQAAFDEtoCYwRHTFi9AlQaDBkG+wMvFkWF3ewQ4pFZmUIoa2JJYkE+SVoqrES+uv1";
		BASE64Encoder base64Encoder = new BASE64Encoder();
		File file = new File("C:\\root\\files\\upload\\012.jpg");
		String encode = base64Encoder.encode(FileUtils.readFileToByteArray(file)).replaceAll(" ","");
	//	String s1=s.split(";base64,")[1];
		System.out.println(encode);
}
}
